package com.txzt.gaea.base.service.impl;

import com.txzt.base.constant.RtnConstant;
import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.api.client.AdminUserRemoteService;
import com.txzt.gaea.base.dto.DictInfoQueryDTO;
import com.txzt.gaea.base.model.DictDetail;
import com.txzt.gaea.base.model.DictInfo;
import com.txzt.gaea.base.service.DictInfoService;
import com.txzt.gaea.base.vo.DictDetailVo;
import com.txzt.gaea.base.vo.DictInfoVo;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.enums.IsDeleteEnum;
import com.txzt.gaea.common.page.PageInfoBT;
import com.txzt.gaea.dto.UserSingleDetailQueryDTO;
import lombok.extern.log4j.Log4j2;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Log4j2
@Service
public class DictInfoServiceImpl extends BaseServiceImpl<DictInfo> implements DictInfoService {

    @Autowired
    private AdminUserRemoteService adminUserRemoteService;

    @Override
    public RtnInfo<PageInfoBT<DictInfoVo>> list(DictInfoQueryDTO dictInfoQueryDTO){
        PageQuery<DictInfoVo> pageQuery = new PageQuery<>(dictInfoQueryDTO.getOffset(), dictInfoQueryDTO.getLimit(), dictInfoQueryDTO);
        PageQuery<DictInfoVo> result = this.sqlManager.pageQuery("dictInfo.selectPageList", DictInfoVo.class,pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT<>(result));
        }
        result.getList().forEach(item -> {
            UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
            userSingleDetailQueryDTO.setUserId(item.getCreateBy());
            item.setCreateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            userSingleDetailQueryDTO.setUserId(item.getUpdateBy());
            item.setUpdateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
        });
        PageInfoBT<DictInfoVo> re = new PageInfoBT<>(result);
        rebuild(re);
        return RtnInfo.success(re);
    }

    @Override
    public int save(DictInfo dictInfo){
        return this.sqlManager.insert(dictInfo);
    }

    @Override
    public int update(DictInfo dictInfo){
        return this.sqlManager.updateTemplateById(dictInfo);
    }

    @Override
    public Integer getLastSort(){
        List<DictInfo> dictInfoList = this.sqlManager.select("dictInfo.selectDictSort", DictInfo.class);
        if (0 == dictInfoList.size() || null == dictInfoList.get(0).getSort()) {
            return 0;
        } else {
            return dictInfoList.get(0).getSort();
        }
    }

    @Override
    public boolean addCheckCode(DictInfo dictInfo){
        LambdaQuery<DictInfo> query = sqlManager.lambdaQuery(DictInfo.class);
        List<DictInfo> orgDictList = query.andEq(DictInfo::getDictCode,dictInfo.getDictCode()).select();
        return 0 >= orgDictList.size();
    }

    @Override
    public boolean updateCheckCode(DictInfo dictInfo){
        LambdaQuery<DictInfo> query = sqlManager.lambdaQuery(DictInfo.class);
        List<DictInfo> orgDictList = query.andEq(DictInfo::getDictCode,dictInfo.getDictCode())
                .andEq(DictInfo::getIsDelete, IsDeleteEnum.NOTDELETE.getCode())
                .andNotEq(DictInfo::getId,dictInfo.getId()).select();
        return 0 >= orgDictList.size();
    }

    @Override
    public int delete(Long id){
        DictInfo dictInfo = new DictInfo();
        dictInfo.setId(id);
        dictInfo.setIsDelete(IsDeleteEnum.DELETE.getCode());
        return this.sqlManager.updateTemplateById(dictInfo);
    }

    @Override
    public RtnInfo<DictInfo> getDictInfo(Long id){
        DictInfo dictInfo = this.selectById(id);
        if (null == dictInfo){
            return RtnInfo.error(RtnConstant.Code.PARAMS_REEOR,"未查到相关信息，请检查上传数据是否正确");
        } else {
            return  RtnInfo.success(dictInfo);
        }
    }

    private void rebuild(PageInfoBT<DictInfoVo> re){
        List<DictInfoVo> list = re.getRows();
        if(CollectionUtils.isEmpty(list)){
            re.setTotal(0);
            return;
        }
//        re.setTotal(list.size());
    }

    @Override
    public Map<String, List<Map<String,Object>>> getAllDictInfo(){
        Map<String, List<Map<String,Object>>> res = new HashMap<>();
        List<DictInfo> dictInfoList = this.sqlManager.select("dictInfo.selectAllList",DictInfo.class);
        List<DictDetailVo> dictDetailList = this.sqlManager.select("dictDetail.selectAllList",DictDetailVo.class);
        dictInfoList.forEach(info -> {
            List<Map<String,Object>> detailList = dictDetailList.stream().filter(detail -> info.getId().equals(detail.getDictId())).map(item -> {
                Map<String,Object> map = new HashMap<>();
                map.put("label",item.getLabel());
                map.put("value",item.getValue());
                map.put("subDictCode",item.getDictCode());
                return map;
            }).collect(Collectors.toList());
            res.put(info.getDictCode(),detailList);
        });
        return res;
    }

    @Override
    public String dictTranslate(String dictCode,String value){
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        LambdaQuery<DictInfo> query = sqlManager.lambdaQuery(DictInfo.class);
        DictInfo dictInfo = query.andEq(DictInfo::getDictCode,dictCode).single();
        if (null == dictInfo){
            return "";
        }

        LambdaQuery<DictDetail> detailLambdaQuery = sqlManager.lambdaQuery(DictDetail.class);
        DictDetail dictDetail = detailLambdaQuery.andEq(DictDetail::getDictId,dictInfo.getId())
                .andEq(DictDetail::getValue,value).single();
        if (null == dictDetail){
            return "";
        }
        return dictDetail.getLabel();
    }

    @Override
    public String getDictValue(String dictCode,String label){
        LambdaQuery<DictInfo> query = sqlManager.lambdaQuery(DictInfo.class);
        DictInfo dictInfo = query.andEq(DictInfo::getDictCode,dictCode).single();
        if (null == dictInfo){
            return null;
        }
        LambdaQuery<DictDetail> detailLambdaQuery = sqlManager.lambdaQuery(DictDetail.class);
        DictDetail dictDetail = detailLambdaQuery.andEq(DictDetail::getDictId,dictInfo.getId())
                .andEq(DictDetail::getLabel,label).single();
        if (null == dictDetail){
            return null;
        }
        return dictDetail.getValue();
    }

    @Override
    public DictDetail selectDictValue(String dictCode,String label){
        LambdaQuery<DictInfo> query = sqlManager.lambdaQuery(DictInfo.class);
        DictInfo dictInfo = query.andEq(DictInfo::getDictCode,dictCode).single();
        if (null == dictInfo){
            return null;
        }
        LambdaQuery<DictDetail> detailLambdaQuery = sqlManager.lambdaQuery(DictDetail.class);
        DictDetail dictDetail = detailLambdaQuery.andEq(DictDetail::getDictId,dictInfo.getId())
                .andEq(DictDetail::getLabel,label).single();
        if (null == dictDetail){
            return null;
        }
        return dictDetail;
    }

    @Override
    public DictDetail getSubDictValue(Long dictId,String label){
        LambdaQuery<DictDetail> detailLambdaQuery = sqlManager.lambdaQuery(DictDetail.class);
        DictDetail dictDetail = detailLambdaQuery.andEq(DictDetail::getDictId,dictId)
                .andEq(DictDetail::getLabel,label).single();
        if (null == dictDetail){
            return null;
        }
        return dictDetail;
    }
}
